﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCF20Model;
using System.Data.Objects;
using CCF20Model;

namespace CCF20Model.FaultHandler
{
    class ProcessMaintenaceHandler : FaultHandlerBase
    {
        public ProcessMaintenaceHandler(IFaultHandler faultHandler)
        {
            this.ccf20Ent = faultHandler.ccf20Ent;
            this.PreviousHandler = faultHandler;
            this.MyVehicle = faultHandler.MyVehicle;
            this.MyFault = faultHandler.MyFault;
        }
        public override void ProcessRequest()
        {

            if (MyFault.CurrentMileage != null)
            {
                // 如果对于同一个保养项目有多个记录，说明是不同次数的保养,取最小的还未做过的一个

                var myMaintenanceGroup = from vmr in ccf20Ent.VehicleMaintenanceRecords
                                         where vmr.IsActive &&
                                               vmr.VehicleID == MyVehicle.VehicleID
                                         group vmr by vmr.AnchiID into fullPriority
                                         let minPriority = fullPriority.Min(f => f.Priority)
                                         select new
                                         {
                                             AnchiID = fullPriority.Key,
                                             MinPriorityService = fullPriority.Where(f => f.Priority == minPriority),
                                             //为了把上次服务记录，传给次数更高的保养项目，要取至少两条记录
                                             // 我们在客户出场时把上次服务记录，传给次数更高的保养项目
                                             //MinPriorityService = fullPriority.OrderBy(f=>f.Priority).Take(2),
                                             RecordCount = fullPriority.Count()
                                         };
                //because we will start a new CCF20Entities for every fault, we no longer need this.
                //((ObjectQuery)myMaintenanceGroup).MergeOption = MergeOption.OverwriteChanges;

                LoggerHelper.LogZICDebug(string.Format("[保养分析] 该IDC的总共保养项目(包括不同次数的）有{0}个",
                                                        MyVehicle.VehicleMaintenanceRecords.Count(m => m.IsActive)));

                foreach (var g in myMaintenanceGroup.ToList())
                {
                    VehicleMaintenanceRecord vmr = g.MinPriorityService.First();
                    LoggerHelper.LogZICDebug(string.Format("[保养分析] 保养项目={0} RecordCount = {1}",vmr.MaintenanceType.Name,g.RecordCount));
                                                      
                    //验证是否已经有相同的保养请求存在
                    VehicleMaintenanceHistory vmh = ccf20Ent.VehicleMaintenanceHistories.Where(
                                                            m => m.IsActive &&
                                                            m.VehicleID == MyVehicle.VehicleID &&
                                                            m.MaintenanceTypeID == vmr.MaintenanceTypeID &&
                                                            m.Priority == vmr.Priority)
                                                            .FirstOrDefault();

                    if (vmh != null)
                    {

                        LoggerHelper.LogZICDebug(string.Format("[保养分析]重复的保养={0},保养里程={1},保养周期={2},次数={3},当前里程={4}，上次服务里程={5}，上次服务时间={6}",
                                                                vmr.MaintenanceType.Name,
                                                                vmr.ServiceMileage,
                                                                vmr.ServicePeriod,
                                                                vmr.Priority,
                                                                MyFault.CurrentMileage,
                                                                vmr.LastServiceMileage,
                                                                vmr.LastServiceDate));
                        continue;
                    }
                    
                    LoggerHelper.LogZICDebug(string.Format("[保养分析]这次需要分析判断的保养项目{6} IDCSimNumber={0} 车辆ID={1} 故障码={2} ServiceMileage={3} ServicePeriod={4}  LastServiceDate={5}  LastServiceMileage={7} Priority={8}",
                                                                    MyFault.IDCSimNumber,
                                                                    MyFault.VehicleID,
                                                                    MyFault.Code,
                                                                    vmr.ServiceMileage,
                                                                    vmr.ServicePeriod,
                                                                    vmr.LastServiceDate,
                                                                    vmr.MaintenanceType.Name,
                                                                    vmr.LastServiceMileage,
                                                                    vmr.Priority
                                                                ));
                    
                    //避免里程，和周期都超过时重复加保养
                    bool IsMaintenanceAdded = false; 
                    if (vmr.ServiceMileage != null && vmr.ServiceMileage > 0 && MyFault.CurrentMileage - vmr.LastServiceMileage + 500 > vmr.ServiceMileage)
                    {
                        //L2-L0+500>L
                        LoggerHelper.LogZICDebug(string.Format("[保养分析]因为里程增加产生保养需求 IDCSimNumber={0} 车辆ID={1} 故障码={2}  CurrentMileage={3}  LastServiceMileage={4} ServiceMileage={5}",
                                                                    MyFault.IDCSimNumber,
                                                                    MyFault.VehicleID,
                                                                    MyFault.Code,
                                                                    MyFault.CurrentMileage,
                                                                    vmr.LastServiceMileage,
                                                                    vmr.ServiceMileage
                                                               ));
                        IsMaintenanceAdded = true;

                    }
                    else if (vmr.ServicePeriod != null && vmr.ServicePeriod > 0 && DateTime.Now + new TimeSpan(15, 0, 0, 0) - new TimeSpan((int)vmr.ServicePeriod, 0, 0, 0) > vmr.LastServiceDate)
                    {
                        //T2-T0+15>T
                        LoggerHelper.LogZICDebug(string.Format("[保养分析]因为保养周期产生保养需求 IDCSimNumber={0} 车辆ID={1} 故障码={2}  ServicePeriod={3}  LastServiceDate={4}",
                                                                   MyFault.IDCSimNumber,
                                                                   MyFault.VehicleID,
                                                                   MyFault.Code,
                                                                   vmr.ServicePeriod,
                                                                   vmr.LastServiceDate
                                                              ));
                        IsMaintenanceAdded = true;
                    }
                    else
                    {
                        //如果ServiceMileage和ServicePeriod没有定义，则不会产生保养需求。
                        LoggerHelper.LogZICDebug(string.Format(@"[保养分析]未产生保养需求 IDCSimNumber={3} 车辆ID={4} 故障码={0} Desc={1} CurrentMileage={2}",
                                                                    MyFault.Code,
                                                                    MyFault.CodeDescription,
                                                                    MyFault.CurrentMileage,
                                                                    MyFault.IDCSimNumber,
                                                                    MyFault.VehicleID));
                        IsMaintenanceAdded = false;
                    }
                    if (IsMaintenanceAdded)
                    {
                        AddMaintenanceHistory(vmr, g.RecordCount);
                        
                    }
                }
            }
            else
            {
                LoggerHelper.LogZICDebug(string.Format(@"[保养分析]该故障码中里程为空"));
            }

            IFaultHandler nextHandler = new ProcessAllFaultHandler(this);
            nextHandler.ProcessRequest();
        }
        private void AddMaintenanceHistory(VehicleMaintenanceRecord vmr, int recordCount)
        {
            MyVehicle.IsMaintenance = true;
            MyVehicle.IsActive = true;
            MyVehicle.LatestActiveTime = DateTime.Now;
            
            
            //如果对于同一个保养项目有多个记录，说明是不同次数的保养
            // 但是我们只有在出场时才把这个保养项目取消
            //vmr.IsActive = false;
            LoggerHelper.LogZICDebug(string.Format("[保养分析] 添加保养需求，保养项目={0} 共有{1}次保养记录,完成第{2}次",
                                            vmr.MaintenanceType.Name,
                                            recordCount,
                                            vmr.Priority));
                
            VehicleMaintenanceHistory vmh = new VehicleMaintenanceHistory();
            vmh.ReceiveDate = DateTime.Now;
            vmh.HappenDate = MyFault.HappenDate;
            vmh.EffectiveReceiveDate = MyFault.EffectiveReceiveDate;
            vmh.VehicleID = vmr.VehicleID;
            vmh.MaintenanceTypeID = vmr.MaintenanceTypeID;
            vmh.ServiceMileage = vmr.ServiceMileage;
            vmh.ServicePeriod = vmr.ServicePeriod;
            vmh.LastServiceDate = vmr.LastServiceDate;
            vmh.LastServiceMileage = vmr.LastServiceMileage;
            vmh.CurrentMileage = MyVehicle.CurrentMileage;
            vmh.IsActive = true;
            vmh.Priority = vmr.Priority;
            vmh.DeviceID = MyVehicle.Devices.First().DeviceID;
            vmh.IsSMSed = false;
            ccf20Ent.VehicleMaintenanceHistories.AddObject(vmh);
        }
    }

}
